﻿#include "MyGLXYZPainter.h"


AsGLXYZPainter::AsGLXYZPainter()
{
	initializeGL();
	m_transformParam.modelMatrix.setToIdentity();
	m_transformParam.projMatrix.setToIdentity();
	m_transformParam.viewMatrix.setToIdentity();
}

AsGLXYZPainter::~AsGLXYZPainter()
{
	clearup();
}

void AsGLXYZPainter::render()
{
	glDisable(GL_DEPTH_TEST);
	m_world.setToIdentity();
	m_camera.setToIdentity();
	m_camera.translate(m_transformParam.xTrans, -m_transformParam.yTrans, m_transformParam.zoomCoe);
	m_camera.rotate(m_transformParam.yRot, 0, 1, 0);
	m_camera.rotate(m_transformParam.xRot, 1, 0, 0);

	QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);
	m_program->bind();
	m_program->setUniformValue(m_projLoc, m_transformParam.projMatrix);
	m_program->setUniformValue(m_mvLoc, m_camera*m_transformParam.modelMatrix);

	glDrawArrays(GL_LINES, 0, 6);
	m_program->release();

}

void AsGLXYZPainter::initVertex()
{
	m_vertex = {
	0,   0,    0,	1, 0, 0,
	0.5, 0,    0,	1, 0, 0,
	0,   0,    0,	0, 1, 0,
	0,   0.5,  0,	0, 1, 0,
	0,   0,    0,	0, 0, 1,
	0,   0,    0.5, 0, 0, 1
	};
}

void AsGLXYZPainter::initializeGL()
{
	initializeOpenGLFunctions();
	m_program = new QOpenGLShaderProgram;
	m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, "D:/gitLab/AiString/NewPCIDemo/jni/src/NewPCIDemoApplication/shader/XYZPainter.vert");
	m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, "D:/gitLab/AiString/NewPCIDemo/jni/src/NewPCIDemoApplication/shader/XYZPainter.frag");
	m_program->link();
	m_program->bind();
	m_projLoc = m_program->uniformLocation("projMatrix");
	m_mvLoc = m_program->uniformLocation("mvMatrix");

	m_vao.create();
	//在栈上创建一个对象来管理opengl的VAO的绑定和解绑过程	
	QOpenGLVertexArrayObject::Binder vaoBinder(&m_vao);

	m_vbo.create();
	m_vbo.bind();
	initVertex();
	//将顶点数组vertex传递到vbo
	m_vbo.allocate(m_vertex.constData(), m_vertex.size() * sizeof(GLfloat));

	setupVertexAttribs();

	m_camera.setToIdentity();
	m_camera.translate(0, 0, -3);

	m_program->release();

}

void AsGLXYZPainter::setupVertexAttribs()
{
	m_vbo.bind();
	QOpenGLFunctions *functions = QOpenGLContext::currentContext()->functions();
	functions->glEnableVertexAttribArray(0);
	functions->glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), 0);
	functions->glEnableVertexAttribArray(1);
	functions->glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
	m_vbo.release();
}

void AsGLXYZPainter::clearup()
{
	if (m_program == nullptr)
	{
		return;
	}
	m_vbo.destroy();
	delete m_program;
	m_program = nullptr;
}
